import axios from 'axios'

// 创建axios实例
const createApiClient = (baseURL) => {
    const client = axios.create({
        baseURL,
        timeout: 30000,
        headers: {
            'Content-Type': 'application/json'
        }
    })

    // 响应拦截器
    client.interceptors.response.use(
        response => response,
        error => {
            console.error('API请求失败:', error)
            return Promise.reject(error)
        }
    )

    return client
}

// 车辆检测API
const vehicleApiClient = createApiClient('http://localhost:8001')

export const VehicleDetectionApi = {
    async healthCheck() {
        try {
            const response = await vehicleApiClient.get('/health')
            return response.data
        } catch (error) {
            throw new Error('车辆检测API服务连接失败')
        }
    },

    async detectVehicle(file) {
        try {
            const formData = new FormData()
            formData.append('file', file)

            const response = await vehicleApiClient.post('/detect', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })

            return response.data
        } catch (error) {
            this.handleError(error)
        }
    },

    handleError(error) {
        if (error.response?.status === 400) {
            throw new Error('请上传有效的图片文件')
        } else if (error.response?.status === 500) {
            throw new Error(error.response.data?.detail || '服务器内部错误')
        } else if (error.code === 'ECONNABORTED') {
            throw new Error('请求超时，请重试')
        } else {
            throw new Error('网络连接失败，请检查后端服务是否启动')
        }
    }
}

// 车牌识别API
const plateApiClient = createApiClient('http://localhost:8000')

export const PlateRecognitionApi = {
    async healthCheck() {
        try {
            const response = await plateApiClient.get('/health')
            return response.data
        } catch (error) {
            throw new Error('车牌识别API服务连接失败')
        }
    },

    async recognizePlate(file) {
        try {
            const formData = new FormData()
            formData.append('file', file)

            const response = await plateApiClient.post('/recognize', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })

            return response.data
        } catch (error) {
            this.handleError(error)
        }
    },

    handleError(error) {
        if (error.response?.status === 400) {
            throw new Error('请上传有效的图片文件')
        } else if (error.response?.status === 500) {
            throw new Error(error.response.data?.detail || '服务器内部错误')
        } else if (error.code === 'ECONNABORTED') {
            throw new Error('请求超时，请重试')
        } else {
            throw new Error('网络连接失败，请检查后端服务是否启动')
        }
    }
}